package oa.hleast.xswl.service.chat.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.xswl.common.constant.ChatDateEnum;
import oa.hleast.xswl.common.constant.ChatterTypeEnum;
import oa.hleast.xswl.pojo.domain.chat.CmsChatAutoReply;
import oa.hleast.xswl.pojo.domain.chat.CmsChatMessageLog;
import oa.hleast.xswl.pojo.vo.chat.CmsChatMessageLogVo;
import oa.hleast.xswl.service.ISysCommonConfigService;
import oa.hleast.xswl.service.ISysDictItemService;
import oa.hleast.xswl.service.IUmsUserService;
import oa.hleast.xswl.service.chat.IChatAutoReplyService;
import oa.hleast.xswl.service.chat.IChatMessageLogService;
import oa.hleast.xswl.service.chat.IChatService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 302
 */
@Service
@Slf4j
@Transactional
@AllArgsConstructor
public class ChatServiceImpl implements IChatService {



    private final ISysDictItemService dictItemService;
    private final IUmsUserService umsUserService;
    private final ISysCommonConfigService commonConfigService;
    private final IChatAutoReplyService chatAutoReplyService;
    private final IChatMessageLogService chatMessageLogService;

    @Override
    public CmsChatAutoReply getWelcome() {
        CmsChatAutoReply chatAutoReply = chatAutoReplyService.getById(0L);
        if (ObjectUtils.isEmpty(chatAutoReply)) {
            log.error("没有找到欢迎值");
            return null;
        }
        return chatAutoReply;
    }



    /**
     * 查询聊天记录
     * 创建时间，ID降序获取数据 >> 集合逆序 >> 添加默认提示回复
     */
    @Override
    public Page<CmsChatMessageLogVo> findChatMessageLog(Long userId, Integer page, Integer limit) {
        //用户的userID作为聊天ID
        Page<CmsChatMessageLog> messageLogPage = chatMessageLogService.page(new Page<>(page, limit), new LambdaQueryWrapper<CmsChatMessageLog>()
                .eq(CmsChatMessageLog::getChatId, userId)
                .orderByDesc(CmsChatMessageLog::getGmtCreate)
                .orderByDesc(CmsChatMessageLog::getId)
        );

        //默认提示回复
        CmsChatAutoReply chatAutoReply = this.getWelcome();
        CmsChatMessageLogVo defaultVo = CmsChatMessageLogVo.builder()
                .id(0L)
                .chatId(userId)
                .type(ChatDateEnum.TXT.name())
                .chatterType(ChatterTypeEnum.SYS.name())
                .userAvatar("")
                .content(chatAutoReply.getReply())
                .build();

        Page<CmsChatMessageLogVo> voPage = new Page<>(page, limit, messageLogPage.getTotal());
        if (messageLogPage.getTotal() == 0) {
            List<CmsChatMessageLogVo> voList = new ArrayList<>();
            voList.add(defaultVo);
            return voPage.setRecords(voList);
        }

        List<CmsChatMessageLogVo> voList = messageLogPage.getRecords().stream().map(this::conversionToLogVo).collect(Collectors.toList());

        //逆序
        Collections.reverse(voList);
        // 第一页时添加默认提示回复
        if (1 == page) {
            voList.add(defaultVo);
        }

        voPage.setRecords(voList);

        return voPage;
    }



    private CmsChatMessageLogVo conversionToLogVo(CmsChatMessageLog pojo) {
        CmsChatMessageLogVo vo = new CmsChatMessageLogVo();
        BeanUtil.copyProperties(pojo, vo);
        //添加格式化时间
        vo.setGmtCreateDate(pojo.getGmtCreate());
        // 添加用户信息
        if (ChatterTypeEnum.USER.name().equals(pojo.getChatterType())) {
            vo.setUserAvatar(umsUserService.getUserDtoById(pojo.getChatId()).getAvatar());
        }
//        if (ChatterTypeEnum.SYS.name().equals(pojo.getChatterType())) {
//            SysCommonConfig hostResult = commonConfigService.getByConfigKey(ConfigKeyConstant.CHAT_SYS_USER_AVATAR);
//            vo.setUserAvatar(hostResult.getValue());
//        }
        return vo;
    }
}
